﻿//本地缓存key
var EDIT_KEY = "editStorageKey";
var access_token = "";
//设置自动保存间隔时间(毫秒)
var SAVA_TIMES = 30 * 1000;

var articleId;

$(function () {
    init();
    loadEditor();
    srollBind();
    var param = {};
    AjaxStart("ajax/WxJsApiAccessToken.ashx?get", param, function (data) {
        if (data.code == 0) {
            var s = sign(data.item.JsApi_Ticket, location.href.split('#')[0]);
            access_token = data.item.Access_Token;
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。    
                appId: data.item.AppId, // 必填，公众号的唯一标识    
                timestamp: s.timestamp, // 必填，生成签名的时间戳    
                nonceStr: s.nonceStr, // 必填，生成签名的随机串    
                signature: s.signature,// 必填，签名，见附录1    
                jsApiList: ['chooseImage', 'uploadImage']
            });
        }
        else
            Alert(data.msg);
    });
});
wx.ready(function () {
    $(".uploadbtn").click(function () {
        var btn = $(this);
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                console.log(res);
                var imgId = res.localIds[0]; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                wx.uploadImage({
                    localId: imgId, // 需要上传的图片的本地ID，由chooseImage接口获得
                    isShowProgressTips: 1, // 默认为1，显示进度提示
                    success: function (res) {
                        var serverId = res.serverId; // 返回图片的服务器端ID
                        var url =
                            "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + access_token + "&media_id=" + serverId;
                        var upapi = "/Client2/Ajax/Upload.ashx?WxImg&url=" + encodeURIComponent(url);
                        console.log(upapi);                        //上传图片
                        $("#article_form").ajaxSubmit({
                            type: 'post',
                            dataType: "json",
                            url: upapi,
                            success: function (data) {
                                console.log(data);
                                wait.dismiss();
                                if ($(btn).attr("id") === "uploadIco") {
                                    restoreRange();
                                    var img = $('<img style = "width:100%;" src = "' + data.item + '"/>');
                                    //插入图片
                                    $(".summernote").summernote("insertNode", img[0]);
                                    $(".panel-body").blur();
                                } else {
                                    $("#file_logo").val("");
                                    $(".logo").attr("src", data.item);
                                }
                            },
                            error: function (XmlHttpRequest, textStatus, errorThrown) {

                            }
                        });

                    }
                });
            }
        });
    });

});
//初始化
function init() {

    articleId = getUrlArgStr("article_id");

    //提交
    $(".top-right").bind("click", function () {

        //表单验证
        if (!call_submit("form"))
            return;

        var title = $("#title").val();
        var content = escape($(".summernote").code());
        var logo = $(".logo").attr("src");
        var is_recommend = $("#check").attr("class").indexOf("fa-check-square-o") != -1 ? 1 : 0;

        if (logo == "img/default.png") {
            toast.show("请上传标题logo");
            return;
        }

        var param = "title=" + title + "&logo=" + logo + "&content=" + content + "&is_recommend=" + is_recommend + "&article_id=" + articleId;
        if (articleId.length == 0) {
            AjaxStart("ajax/fc_article.ashx?addarticle", param, function (data) {
                if (data.code == 0) {
                    delSava();
                    //发布成功;
                    Alert("添加成功，请完善设置");
                    setTimeout(function () { window.location.href = 'makeset.html?id=' + data.item }, 1000);
                }
            });
        }
        else {
            ajax.ArticleUpdate(param, function (data) {
                if (data.code == 0) {
                    delSava();
                    history.go(-1);
                }
            });
        }
    });

    $("#check").bind("click", function () {
        if ($(this).attr("class").indexOf("fa-check-square-o") != -1) {
            //选中状态  改变为未选中状态 
            $(this).removeClass("fa-check-square-o");
            $(this).addClass("fa-square-o");
        }
        else {
            $(this).removeClass("fa-square-o");
            $(this).addClass("fa-check-square-o");
        }
    });


    // 添加视频

    // 添加连链接

    // 加粗
    $(".fa-bold").on("click", function () {
        bold();
    });

}

//添加链接
function insertLink(dValue) {
    // 输入框
    GlInputBox({
        title: "输入链接地址",
        value: dValue,
        okClick: function (val) {

            //获取到当前选中的文字
            var selectedVal = getSelectTxt();
            var html = '<a href = "' + val + '" target = "_blank">' + selectedVal + '</a>';
            insertHtml(html);
        }
    });
}

//加粗
function bold() {
    $('.summernote').summernote('bold');
}

//获取当前选中的文字
function getSelectTxt() {

    var range = document.createRange();
    range.setStart(currentSelection.startContainer,
										currentSelection.startOffset);
    range.setEnd(currentSelection.endContainer,
										currentSelection.endOffset);

    //获取到当前选中的文字
    var selectedVal = range.toString();
    return selectedVal;
}


/**
* 弹出输入框
* 
* @param val
*/
function popInput(defaultVal) {

    // 输入框
    GlInputBox({
        title: "输入视频地址",
        value: defaultVal,
        okClick: function (val) {
            if (val.indexOf("http") == -1) {
                GlToast({
                    body: "没有检测到视频地址",
                    onClose: function () {
                        popInput(val);
                    }
                });
                return;
            }
            if (!val.startWith("http")) {

                //去掉多余的字符
                val = val.substring(val.indexOf("http"));
            }

            var url = val;

            // 如果输入的是MP4网络路径
            if (url.endWith(".mp4") || url.indexOf(".mp4?") != -1) {
                insertVideo(url);
                return;
            }

            ajaxJson({
                url: "/Client/Ajax/HttpSource.ashx?GetVideo",
                data: {
                    url: url
                },
                callback: function (data) {
                    if (url.indexOf("v.youku.com/") != -1) {

                        // 优酷视频
                        var ifm = '<iframe class = "youku-video" src="' + data
								+ '" frameborder=0 allowfullscreen></iframe>';
                        insertHtml(ifm, true);
                        youkuIfram();
                    } else if (url.indexOf("view.inews.qq.com/") != -1
							|| url.indexOf("mp.weixin.qq.com/") != -1
							|| url.indexOf("v.qq.com/") != -1) {

                        // 腾讯视频、微信视频、腾讯新闻
                        insertTencentVideo(data.vid, data.thumb);
                    } else if (url.indexOf("toutiao.com/") != -1) {

                        // 今日头条
                        var html = '<video poster = "'
								+ data.thumb
								+ '" videoid = "'
								+ data.videoid
								+ '" width = "100%" height = "auto" controls></video>';
                        insertHtml(html, true);
                    } else {

                        // 微博、内涵段子视频等等
                        insertVideo(data.src, data.thumb);
                    }
                }
            });
        }
    });
}

/**
* 优酷视频宽度适应
*/
function youkuIfram() {
    var w = $(window).width() - 30;
    var h = w * 9 / 16;
    $(".youku-video").css("width", w + "px");
    $(".youku-video").css("height", h + "px");

}

//加载编辑器
function loadEditor() {
    $('.summernote').summernote({
        lang: 'zh-CN',
        height: 0,
        toolbar: [['fontsize', ['fontsize']]]
    });
    savaRange();
    if (articleId.length == 0) {
        loadSava();
    }
    else {
        loadData();
    }
    setTimeout("autoSava()", SAVA_TIMES);
    $(".panel-body").css("min-height", "240px");


    $(".note-editor").append($("#toolBody").html());
    $("#toolBody").remove();

}

//获取数据
function loadData() {
    ajax.ArticleDetail("id=" + articleId, function (data) {
        $("#title").val(data.item.title);
        $(".logo").attr("src", data.item.logo);
        $(".summernote").code(data.item.content);

        if (!data.item.is_recommend) {
            $("#check").removeClass("fa-check-square-o");
            $("#check").addClass("fa-square-o");
        }
    });
}

//滚动事件
function srollBind() {
    $(window).bind("scroll", function () {

        // 当滚动条滚动时
        var scollTop = $(this).scrollTop() + $(this).height();
        var scollH = $(document).height();

        //如果距离底部的距离小于100  并且 是在向上滑
        if (scollH - scollTop < 200) {
            $(".tool-body").removeClass("tool-body-bottom");
        }
        else {
            $(".tool-body").addClass("tool-body-bottom");
        }
        prevTop = scollTop;
        return false;
    });
}

//重新显示图片
function resetLogo(src) {
    $(".logo").attr("src", src);
}


/**
* 插入有效的视频地址
* 
* @param src
*/
function insertVideo(src, thumb) {
    if (thumb == null) {
        thumb = "";
    }
    var html = '<video poster = "' + thumb + '" src = "' + src
			+ '" width = "100%" height = "auto" controls></video>';
    insertHtml(html, true);
}

/**
* 插入腾讯视频地址
* 
* @param src
*/
function insertTencentVideo(vid, thumb) {
    if (thumb == null) {
        thumb = "";
    }
    var html = '<video poster = "' + thumb + '" vid = "' + vid
			+ '" width = "100%" height = "auto" controls></video>';
    insertHtml(html, true);
}

/**
* 插入html代码
* 
* @param html
* @param insetP:是否添加p标签
*/
function insertHtml(html, insetP) {

    // 不能获取焦点 否则ios会跳到顶
    // $(".panel-body").focus();
    restoreRange();

    var tag = null;
    if (insetP) {
        tag = $("<p>" + html + "</p>");
    }
    else {
        tag = $(html);
    }

    // 插入图片
    $(".summernote").summernote("insertNode", tag[0]);
    $(".panel-body").blur();
}

//客户端上传了正文内容图片
function addContentImg(src) {
    var img = '<img style = "width:100%;" src = "' + src + '"/>';
    insertHtml(img, true);
}

//记录输入光标位置
var currentSelection;

//保存Range
function savaRange() {
    if ($(".panel-body").is(":focus")) {
        //toast.show('保存rang');
        $(".summernote").summernote("savaRange");
        //console.log('保存rang');
        var selection = window.getSelection();
        var range = selection.getRangeAt(0);
        currentSelection = {
            "startContainer": range.startContainer,
            "startOffset": range.startOffset,
            "endContainer": range.endContainer,
            "endOffset": range.endOffset
        };
    }
    else {
        //console.log('不保存rang');
    }
    setTimeout("savaRange();", 200);
}

//恢复Rang
function restoreRange() {

    var selection = window.getSelection();
    selection.removeAllRanges();
    var range = document.createRange();
    range.setStart(currentSelection.startContainer,
										currentSelection.startOffset);
    range.setEnd(currentSelection.endContainer,
										currentSelection.endOffset);
    selection.addRange(range);
}

//自动保存
function autoSava() {
    sava();
    setTimeout("autoSava()", SAVA_TIMES);
}

//保存编辑
function sava() {

    //获取输入的内容
    var content = $(".summernote").code();
    setStorage(EDIT_KEY, content);
}

//保存编辑
function loadSava() {
    var content = getStorage(EDIT_KEY);
    if (content != null) {
        $(".summernote").code(content);
    }
}

//删除保存
function delSava() {
    delStorage(EDIT_KEY);
}



